<template>
  <div class="auth-container">
    <div class="auth-dialog">
      <!-- 左侧登录区域 -->
      <div class="auth-content">
        <div class="auth-header">
          <div class="auth-tabs">
            <div 
              class="tab-item" 
              :class="{ active: activeTab === 'login' }"
              @click="activeTab = 'login'"
            >
              登录
            </div>
            <div 
              class="tab-item" 
              :class="{ active: activeTab === 'register' }"
              @click="activeTab = 'register'"
            >
              注册
            </div>
          </div>
        </div>

        <!-- 登录表单 -->
        <div v-show="activeTab === 'login'" class="form-container">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
            <el-form-item prop="userName">
              <el-input v-model="loginForm.userName" placeholder="请输入用户名">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <div class="form-options">
              <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
              <a href="javascript:;" class="forget-link">忘记密码？</a>
            </div>
            <el-button type="primary" class="submit-btn" @click="handleLogin">
              登录
            </el-button>
          </el-form>
        </div>

        <!-- 注册表单 -->
        <div v-show="activeTab === 'register'" class="form-container">
          <el-form ref="registerForm" :model="registerForm" :rules="registerRules">
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="请输入用户名">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="请输入密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-button type="primary" class="submit-btn" @click="handleRegister">
              注册
            </el-button>
          </el-form>
        </div>
      </div>

      <!-- 右侧动效区域 -->
      <div class="auth-banner">
        <div class="tech-circles">
          <div class="circle c1"></div>
          <div class="circle c2"></div>
          <div class="circle c3"></div>
        </div>
        <div class="tech-lines">
          <div class="line l1"></div>
          <div class="line l2"></div>
          <div class="line l3"></div>
        </div>
        <div class="banner-content">
          <div class="tech-icon">
            <div class="pulse-ring"></div>
            <el-icon><Monitor /></el-icon>
          </div>
          <h2>智能创新 · 科技引领</h2>
          <p>让创意激发无限可能</p>
        </div>
      </div>

      <!-- 关闭按钮 -->
      <div class="close-btn" @click="handleClose">
        <el-icon><Close /></el-icon>
      </div>

      <!-- 添加验证组件 -->
      <vue-verify
        ref="verify"
        v-if="stateVerify"
        @success="success"
        mode="pop"
        :captchaType="'blockPuzzle'"
      />
    </div>
  </div>
</template>

<script>
import { useAuthStore, useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import VueVerify from "@/components/verifition/Verify.vue"

export default {
  name: 'LoginAndRegister',
  components: {
    VueVerify
  },
  setup() {
    const authStore = useAuthStore()
    const userStore = useUserStore()
    const { authDialog, loginDialog } = storeToRefs(authStore)
    
    return {
      authStore,
      userStore,
      authDialog,
      loginDialog
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    
    return {
      activeTab: 'login',
      loginForm: {
        userName: '',
        password: '',
        remember: false,
        captcha: {}
      },
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', validator: validatePass }
        ]
      },
      loginRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]
      },
      timer: null,
      countdown: 60,
      stateVerify: false,
      captchaType: 'blockPuzzle'
    }
  },
  methods: {
    handleLogin() {
      if (!this.$refs.loginForm) {
        console.error('Login form not found')
        return
      }
      
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const userName = this.loginForm.userName
          const password = this.loginForm.password
          
          if (!userName) {
            this.$message.warning("请输入帐号")
            return
          }
          if (!password) {
            this.$message.warning("请输入登录密码")
            return
          }
          
          this.$nextTick(() => {
            try {
              this.stateVerify = true
              this.$nextTick(() => {
                if (this.$refs.verify) {
                  this.$refs.verify.show()
                } else {
                  throw new Error('Verify component not found')
                }
              })
            } catch (error) {
              console.error('Error showing verification:', error)
              this.$message.error('验证码组件加载失败')
            }
          })
        }
      })
    },
    
    async success(data) {
      try {
        this.loginForm.captcha = {
          captchaVerification: data.captchaVerification
        }
        
        await this.doLogin()
      } catch (error) {
        console.error('Verification failed:', error)
        this.$message.error(error.message || '验证失败')
      }
    },
    
    async doLogin() {
      try {
        const loginData = {
          userName: this.loginForm.userName.trim(),
          password: this.loginForm.password,
          remember: this.loginForm.remember,
          captcha: this.loginForm.captcha
        }
        
        await this.userStore.login(loginData)
        
        this.loginForm.captcha = {}
        this.stateVerify = false
        
        if (this.loginForm.remember) {
          localStorage.setItem('rememberedUser', this.loginForm.userName)
        } else {
          localStorage.removeItem('rememberedUser')
        }
        
        this.authStore.clearDialog()
        
      } catch (error) {
        this.loginForm.captcha = {}
        this.stateVerify = false
        console.error('Login failed:', error)
        this.$message.error(error.message || '登录失败')
      }
    },
    async handleRegister() {
      try {
        await this.userStore.register(this.registerForm)
        this.activeTab = 'login'
      } catch (error) {
        console.error('Register failed:', error)
      }
    },
    handleClose() {
      this.authStore.clearDialog()
    }
  },
  created() {
    const rememberedUser = localStorage.getItem('rememberedUser')
    if (rememberedUser) {
      this.loginForm.userName = rememberedUser
      this.loginForm.remember = true
    }
  },
  watch: {
    activeTab(newVal) {
      this.authStore.setLoginDialog(newVal === 'login')
    },
    loginDialog: {
      handler(val) {
        this.activeTab = val ? 'login' : 'register'
      },
      immediate: true
    }
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    this.stateVerify = false
    this.loginForm.captcha = {}
  }
}
</script>

<style lang="scss" scoped>
.auth-container {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.75);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.auth-dialog {
  width: 900px;
  height: 560px;
  background: #fff;
  border-radius: 20px;
  display: flex;
  overflow: hidden;
  position: relative;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  animation: dialogShow 0.3s ease-out;
}

.auth-content {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

.auth-header {
  margin-bottom: 40px;
}

.auth-tabs {
  display: flex;
  gap: 40px;
  justify-content: center;
}

.tab-item {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 8px 4px;
  position: relative;
  transition: all 0.3s;

  &.active {
    color: #333;
    font-weight: 600;

    &:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 3px;
      background: linear-gradient(90deg, #1a73e8, #34a853);
      border-radius: 3px;
      animation: tabLineShow 0.3s ease-out;
    }
  }

  &:hover {
    color: #666;
  }
}

.form-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  animation: formShow 0.3s ease-out;
}

:deep(.el-input) {
  .el-input__wrapper {
    background: #f5f7fa;
    border: none;
    box-shadow: none;
    height: 50px;
    padding: 0 15px;
    transition: all 0.3s;

    &:hover, &:focus-within {
      background: #eef2f7;
      box-shadow: 0 0 0 1px #1a73e8;
    }
  }

  .el-input__prefix {
    font-size: 20px;
    color: #909399;
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.forget-link {
  color: #1a73e8;
  text-decoration: none;
  font-size: 14px;
  
  &:hover {
    text-decoration: underline;
  }
}

.submit-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  border: none;
  background: linear-gradient(90deg, #1a73e8, #34a853);
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(26, 115, 232, 0.3);
  }
}

.auth-banner {
  width: 400px;
  background: linear-gradient(135deg, #1a73e8, #34a853);
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.tech-circles {
  position: absolute;
  inset: 0;

  .circle {
    position: absolute;
    border-radius: 50%;
    border: 2px solid rgba(255, 255, 255, 0.1);
    animation: rotate linear infinite;

    &.c1 {
      width: 300px;
      height: 300px;
      top: -100px;
      right: -100px;
      animation-duration: 20s;
    }

    &.c2 {
      width: 200px;
      height: 200px;
      bottom: 50px;
      left: -50px;
      animation-duration: 15s;
      animation-direction: reverse;
    }

    &.c3 {
      width: 100px;
      height: 100px;
      bottom: 100px;
      right: 50px;
      animation-duration: 10s;
    }
  }
}

.tech-lines {
  position: absolute;
  inset: 0;

  .line {
    position: absolute;
    background: linear-gradient(90deg, 
      transparent,
      rgba(255, 255, 255, 0.2),
      transparent
    );
    height: 1px;
    width: 100%;
    animation: lineMove 3s ease-in-out infinite;

    &.l1 { top: 20%; animation-delay: 0s; }
    &.l2 { top: 50%; animation-delay: 1s; }
    &.l3 { top: 80%; animation-delay: 2s; }
  }
}

.banner-content {
  text-align: center;
  color: #fff;
  position: relative;
  z-index: 1;
}

.tech-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 30px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .el-icon {
    font-size: 40px;
    color: #fff;
  }

  .pulse-ring {
    position: absolute;
    inset: -10px;
    border: 2px solid rgba(255, 255, 255, 0.5);
    border-radius: 50%;
    animation: pulse 2s ease-out infinite;
  }
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  color: #fff;

  &:hover {
    background: rgba(0, 0, 0, 0.4);
    transform: rotate(90deg);
  }
}

@keyframes dialogShow {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes formShow {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes tabLineShow {
  from {
    width: 0;
    opacity: 0;
  }
  to {
    width: 100%;
    opacity: 1;
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes lineMove {
  0% {
    transform: translateX(-100%);
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    transform: translateX(100%);
    opacity: 0;
  }
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

// 添加验证码输入框的样式
.code-input {
  display: flex;
  gap: 10px;
  
  .el-input {
    flex: 1;
  }
  
  .el-button {
    width: 120px;
    height: 50px;
  }
}
</style>
